package com.wechat.controller;


import sky.wechat_tools.api.MainService;
import sky.wechat_tools.impl.WxService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@Controller
@RequestMapping(value = "/wechat")
public class Wechat {
    private MainService iService = new WxService();


    @GetMapping
    @ResponseBody
    public String check(
            @RequestParam(value = "signature") String signature,
            @RequestParam(value = "timestamp") String timestamp,
            @RequestParam(value = "nonce") String nonce,
            @RequestParam(value = "echostr") String echostr) {
        System.out.println(signature);
        if (iService.checkSignature(signature, timestamp, nonce, echostr)) {
            return echostr;
        }
        return null;
    }

    @PostMapping
    public void handle(PrintWriter out, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 默认回复一个"success"
        //  String responseMessage = "fail";
        //   PrintWriter out = response.getWriter();
        try {

            // 微信服务器推送过来的是XML格式。
                /*WxXmlMessage wx = XStreamTransformer.fromXml(WxXmlMessage.class, request.getInputStream());
                System.out.println("消息：\n " + wx.toString());*/
            String token = "zhejiushigetoken";
            String encodingAesKey = "B3i73KJbgcMcldmNjXM3hXkgdSE6WrFuSIRNF9RFG6c";
            String appId = "wx020a8a9e9cbacbd5";

            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String msg_signature = request.getParameter("msg_signature");

            System.out.println("type:" + request.getContentType());
            // 容纳请求消息实体的字节数组
            byte[] dataOrigin = new byte[request.getContentLength()];
            InputStream aaa = request.getInputStream();
            // 得到请求消息的数据输入流
            DataInputStream in = new DataInputStream(request.getInputStream());
            // 根据长度，将消息实体的内容读入字节数组dataOrigin中
            in.readFully(dataOrigin);
            // 关闭数据流
            in.close();
            //byte数组转String并用uft-8编码
            String requestString = new String(dataOrigin,"utf-8");
            System.out.println("reqcontent:" + requestString);

          /*
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader sr = new StringReader(requestString);
            InputSource is = new InputSource(sr);
            Document document = db.parse(is);

            Element root = document.getDocumentElement();
            NodeList nodelist1 = root.getElementsByTagName("Encrypt");
            String encrypt = nodelist1.item(0).getTextContent();
            String format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";
            String fromXML = String.format(format, encrypt);

            WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
            String result2 = pc.decryptMsg(msg_signature, timestamp, nonce, fromXML);
            System.out.println("解密后明文: " + result2);
            */

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

}
